/**
 * Created by wdj on 16/9/6.
 * store
 */

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const SHOW_ALL = 'all'
export const SHOW_FAVORITE = 'favorite'

// 需要维护的状态
const state = {
    notes: [],
    activeNote: {},
    show: '',
    ready: false
}

function saveNotesToStorage (state) {
    window.localStorage['notesData'] = JSON.stringify(state)
}

const mutations = {
    // 初始化 state
    INIT_STORE (state, data) {
        state.notes = data.notes
        state.show = data.show
        state.activeNote = data.activeNote
        state.ready = true
    },
    // new
    NEW_NOTE (state) {
        let newNote = {
            id: +Date.now(),
            title: '',
            content: '',
            favorite: false
        }

        state.notes.push(newNote)
        state.activeNote = newNote
        saveNotesToStorage(state)
    },
    // edit
    EDIT_NOTE (state, note) {
        state.activeNote = note
        for (let i = 0; i < state.notes.length; i++) {
            if (state.notes[i].id === note.id) {
                state.notes[i] = note
                break
            }
        }
        saveNotesToStorage(state)
    },
    // delete
    DELETE_NOTE (state) {
        state.notes.$remove(state.activeNote)
        state.activeNote = state.notes[0] || {}
        saveNotesToStorage(state)
    },
    // toggle
    TOGGLE_FAVORITE (state) {
        state.activeNote.favorite = !state.activeNote.favorite
        saveNotesToStorage(state)
    },
    // set show all
    SET_SHOW_ALL (state, show) {
        state.show = show
        if (show === SHOW_FAVORITE) {
            state.activeNote = state.notes.filter(note => note.favorite)[0] || {}
        } else {
            state.activeNote = state.notes[0] || {}
        }
        saveNotesToStorage(state)
    },
    // set active
    SET_ACTIVE_NOTE (state, note) {
        state.activeNote = note
        saveNotesToStorage(state)
    }

}

export default new Vuex.Store({
    state,
    mutations
})
